package com.colorfruit.admin.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.colorfruit.admin.business.dao.GlobalProcessionControlMapper;
import com.colorfruit.admin.business.dao.PreShelfOrderMapper;
import com.colorfruit.admin.business.dao.StatisticProductMapper;
import com.colorfruit.admin.business.service.ShopHomeService;
import com.colorfruit.admin.pojo.constant.CommonConstant;
import com.colorfruit.admin.pojo.constant.RedisConstant;
import com.colorfruit.admin.pojo.entity.GlobalProcessionControl;
import com.colorfruit.admin.pojo.entity.StatisticProduct;
import com.colorfruit.admin.pojo.enums.GlobalStatusEnum;
import com.colorfruit.admin.pojo.vo.preonshelf.PreOnShelfVoTotal;
import com.colorfruit.admin.pojo.vo.product.ProductTree;
import com.colorfruit.framework.common.util.BusinessUtil;
import com.colorfruit.framework.model.admin.CommonDate;
import com.colorfruit.admin.pojo.vo.preonshelf.PreOnShelfVo;
import com.colorfruit.framework.common.util.DataConvertUtil;
import com.colorfruit.framework.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
public class ShopHomeImpl implements ShopHomeService {

    @Autowired
    PreShelfOrderMapper preShelfOrderMapper;  //  预上架产品订单

    @Autowired
    StatisticProductMapper statisticProductMapper; // 产品统计

    @Autowired
    GlobalProcessionControlMapper globalProcessionControlMapper; //全局控制

    @Autowired
    RedisCache redisCache; //redis 操作方法

    @Override
    public String getLeftBanner() {
        try {
            log.info("[service] [IN] getLeftBanner param : prePurchaseOrderIds " );
            CommonDate commonDate = BusinessUtil.getCommonDate();
            //获取当前系统的状态
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();
            List<PreOnShelfVo> preOnShelfVos = null;
            StringBuffer bannerBuffer = new StringBuffer();
            boolean containActivity = false; //活动
            boolean containNewArrival = false; //新品
            boolean containHotSale = false; //热销
            //活动 跟 新品
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                preOnShelfVos = preShelfOrderMapper.selectContainLabelListWithGlobal(globalProcessionControl.getId());
            }else {
                preOnShelfVos = preShelfOrderMapper.selectContainLabelList(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd());
            }
            for (PreOnShelfVo preOnShelfVo : preOnShelfVos){
                //判断当日是否有爆款产品
                if (preOnShelfVo.getGoodLabel().contains(CommonConstant.ACTIVITY)){
                    containActivity = true;
                }
                //判断当日是否有新品
                if (preOnShelfVo.getGoodLabel().contains(CommonConstant.NEW_ARRIVAL)){
                    containNewArrival = true;
                }
            }
            //热销
            List<StatisticProduct> statisticProducts = null;
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                statisticProducts = statisticProductMapper.selectProductWithHotByGlobal(globalProcessionControl.getId());
            }else {
                statisticProducts = statisticProductMapper.selectProductWithHot(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd());
            }
            if (statisticProducts.size() > 0){
                containHotSale = true;
                StatisticProduct statisticProduct = statisticProducts.get(0);
                Integer weekSaleNumber = statisticProduct.getWeekSaleNumber();
                if (weekSaleNumber > 0){
                }
            }
            if (containActivity){
                bannerBuffer.append(CommonConstant.ACTIVITY_NAME).append(",");
            }
            if (containNewArrival){
                bannerBuffer.append(CommonConstant.NEW_ARRIVAL_NAME).append(",");
            }
            if (containHotSale){
                bannerBuffer.append(CommonConstant.HOT_SALE_NAME).append(",");
            }
            //如果是下单阶段, 查询当天的水果
            List<String> fruitList = null;
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                fruitList = preShelfOrderMapper.selectShelfNameWitTimeByGlobal(globalProcessionControl.getId());
            }else {
                //否则查询近一周的
                fruitList = preShelfOrderMapper.selectShelfNameWitTime(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd());
            }
            int fruitSize = fruitList.size();
            if (fruitSize > 0){
                for (int i = 0; i< fruitSize ; i++){
                    bannerBuffer.append(fruitList.get(i));
                    if (i < fruitSize -1){
                        bannerBuffer.append(",");
                    }
                }
            }
            log.info("[service] [OUT] getLeftBanner success,  ");
            redisCache.putCacheWithExpireTime(RedisConstant.HOME_LEFT_BANNER, bannerBuffer.toString(), 3600 * 1);
            return bannerBuffer.toString();
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<PreOnShelfVo> selectActivityProductList() {
        try {
            log.info("[service] [IN] selectActivityProductList  :  " );
            //1. 获取全局状态
            CommonDate commonDate = BusinessUtil.getCommonDate();
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();
            //2.查询预采购订单数据
            List<PreOnShelfVo> preShelfOrderList = null;
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                preShelfOrderList = preShelfOrderMapper.selectActivityList(commonDate.getTheDayBegin(), commonDate.getTheDayEnd(), CommonConstant.ACTIVITY);
            }else {
                //否则查询近一周的
                preShelfOrderList = preShelfOrderMapper.selectActivityList(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd(), CommonConstant.ACTIVITY);
            }
            String str = JSON.toJSONString(preShelfOrderList);
            redisCache.putCache(RedisConstant.HOME_ACTIVITY_LIST, str);
            log.info("[service] [OUT] selectActivityProductList success,  ");
            return preShelfOrderList;
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }



    @Override
    public List<PreOnShelfVo> selectNewArrivalProductList() {
        try {
            log.info("[service] [IN] selectNewArrivalProductList  :  " );
            //1. 获取全局状态
            CommonDate commonDate = BusinessUtil.getCommonDate();
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();
            //2.查询预采购订单数据
            List<PreOnShelfVo> preShelfOrderList = null;
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                preShelfOrderList = preShelfOrderMapper.selectActivityListWithGlobal(globalProcessionControl.getId(), CommonConstant.NEW_ARRIVAL);
            }else {
                //否则查询近一周的
                preShelfOrderList = preShelfOrderMapper.selectActivityList(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd(), CommonConstant.NEW_ARRIVAL);
            }
            String str = JSON.toJSONString(preShelfOrderList);
            redisCache.putCache(RedisConstant.HOME_NEW_ARRIVAL_LIST, str);
            log.info("[service] [OUT] selectNewArrivalProductList success,  ");
            return preShelfOrderList;
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<PreOnShelfVo> selectHotSaleProductList() {
        try {
            log.info("[service] [IN] selectHotSaleProductList  :  " );
            //1. 获取全局状态
            CommonDate commonDate = BusinessUtil.getCommonDate();
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();
            //2.查询预采购订单数据
            List<PreOnShelfVo> preShelfOrderList = null;
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                preShelfOrderList = preShelfOrderMapper.selectHotSaleProductListWithGlobal(globalProcessionControl.getId());
            }else {
                //否则查询近一周的
                preShelfOrderList = preShelfOrderMapper.selectHotSaleProductList(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd());
            }
            String str = JSON.toJSONString(preShelfOrderList);
            redisCache.putCache(RedisConstant.HOME_HOT_SALE_LIST, str);
            log.info("[service] [OUT] selectHotSaleProductList success,  ");
            return preShelfOrderList;
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<PreOnShelfVoTotal> selectHomeNormalProductList(String productType, int page, int size) {
        try {
            log.info("[service] [IN] selectHomeNormalProductList  param : productType = {}, page = {}, size = {}", productType, page, size );
            //1. 获取全局状态
            CommonDate commonDate = BusinessUtil.getCommonDate();
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();
            //2.查询预采购订单数据
            List<PreOnShelfVo> preShelfOrderList = null;
            if (globalProcessionControl.getRecordStatus() == GlobalStatusEnum.SHOPPING.getCode()){
                preShelfOrderList = preShelfOrderMapper.selectHomeProductListWithGlobal(globalProcessionControl.getId(), productType, size);
            }else {
                //否则查询近一周的
                preShelfOrderList = preShelfOrderMapper.selectHomeProductList(commonDate.getSevenDayBeforeBegin(), commonDate.getTheDayEnd(), productType, size);
            }
            List<PreOnShelfVoTotal> preOnShelfVoTotalList = new ArrayList<>();
            for (PreOnShelfVo preOnShelfVo : preShelfOrderList){
                log.info(preOnShelfVo.getProductType());
                //需要丢到的产品池
                Iterator<PreOnShelfVoTotal> iterator = preOnShelfVoTotalList.iterator();
                boolean canMatch = false;
                while (iterator.hasNext()) {
                    PreOnShelfVoTotal preOnShelfVoTotal = iterator.next();
                    if (preOnShelfVoTotal.getProductType().equals(preOnShelfVo.getProductType())) {
                        canMatch = true;
                        preOnShelfVoTotal.getPreOnShelfVoList().add(preOnShelfVo);
                    }
                }
                if (!canMatch) {
                    PreOnShelfVoTotal preOnShelfVoTotal = new PreOnShelfVoTotal();
                    preOnShelfVoTotal.setProductType(preOnShelfVo.getProductType());
                    preOnShelfVoTotal.getPreOnShelfVoList().add(preOnShelfVo);
                    preOnShelfVoTotalList.add(preOnShelfVoTotal);
                }
            }

            String str = JSON.toJSONString(preOnShelfVoTotalList);
            redisCache.putCache(RedisConstant.HOME_NORMAL_PRODUCT_LIST + productType + page + size, str);
            log.info("[service] [OUT] selectHomeNormalProductList success,  ");
            return preOnShelfVoTotalList;
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }
}
